import Vue from "vue";
import Router from "vue-router";

import Layout from '../view/layout/Layout.vue'   
 
Vue.use(Router);

//获取原型对象上的push函数
const originalPush = Router.prototype.push;
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};


function createManagerRouter(key, title, image, menuId, menuKey){
  menuKey=menuKey?menuKey:menuId
  return {
    path: '', 
    component: Layout,    
    meta: {  },
    name: `${key}-manager-layout`,
    children: [
      {
        path: `/${key}-manager`,
        name: `${key}-manager`,
        component: () => import("@/view/manager/index.vue"),
        meta: { title: title, icon: image, noCache: true,query:{menuId},menuKey }
      },
    ]
  }
}

function createManagerListRouter(key, title, image, menuId, menuKey){
  menuKey=menuKey?menuKey:menuId
  console.log("menuKey=",menuKey);
  return {
    path: '', 
    component: Layout,    
    meta: {  },
    name: `${key}-manager-list-layout`,
    children: [
      {
        path: `/${key}-manager-list`,
        name: `${key}-manager-list`,
        component: () => import("@/view/manager-list/index.vue"),
        meta: { title, icon: image, noCache: true,query:{menuId}, menuKey }
      },
    ]
  }
}


function createMemberRouter(key, title, image, menuId, menuKey, componentUrl="member/index.vue"){
  menuKey=menuKey?menuKey:menuId
  return {
    path: '', 
    component: Layout,    
    meta: {  },
    name: `${key}-dept-layout`,
    children: [
      {
        path: `/${key}-dept`,
        name: `${key}-dept`,
        component: () => import( `@/view/${componentUrl}`),
        meta: { title, icon: image, noCache: true,query:{menuId},menuKey }
      },
    ]
  }
}

function createRegionRouter(key, title, image, menuId, menuKey){
  menuKey=menuKey?menuKey:menuId
  return {
    path: '', 
    component: Layout,    
    meta: {  },
    name: `${key}-region-layout`,
    children: [
      {
        path: `/${key}-region`,
        name: `${key}-region`,
        component: () => import("@/view/region/index.vue"),
        meta: { title, icon: image, noCache: true,query:{menuId} ,menuKey}
      },
    ]
  }
}

function createCommonRouter(key, title, image, menuId, menuKey, file){
    menuKey=menuKey?menuKey:menuId
    return {
      path: '', 
      component: Layout,    
      meta: {  },
      name: `${key}-layout`,
      children: [
        {
          path: `/${key}`,
          name: `${key}`,
          component: () => import( `@/view/${file}`),
          meta: { title, icon: image, noCache: true,query:{menuId},menuKey }
        },
      ]
    }
  }




// 自治区: 13800000000   
// 盟市: 	15800010095      
// 旗县: 	15800040202
// 乡镇: 	15800040301
// 村屯: 	15800040001

// 盟市成员单位：  	15800010112
// 专家管理员       15800010120
// 避难场所管理员   15800010121
// 救援队伍管理员   15800010117
// 防护目标管理员   15800010119
// 应急物资    15800010118
// 事业单位    15800010116 
// 内设机构    15800010115

//  单位领导(user)->专家(user)->避难场所(org)->防护目标(org)-救援队伍(admin)->事业单位(org)
/**
 * 通用的页面路由使用统一的方法创建，非通用路由需要自定义方法或者直接写在Map中
 */
export const routerMap={
  // [manager-list、people、member、region、member-org-own] 考虑使用[entity]来共用
  //原始菜单
  "1000000001": createCommonRouter("dw","党委管理员","dw2.png","1000000001","","manager/info/index.vue"),
  "1000000002": createCommonRouter("zf","政府管理员","zf2.png","1000000002","","manager/info/index.vue"),
  "1000000017": createCommonRouter("gw","工委管理员","zf2.png","1000000017","","manager/info/index.vue"),
  "1000000003": createCommonRouter("ms","盟市指挥体系","zhtx2.png","1000000003","","region/index.vue"),
  "1000000004": createCommonRouter("qx","旗县指挥体系","zhtx2.png","1000000004","","region/index.vue"),
  "1000000005": createCommonRouter("xz","乡镇指挥体系","zhtx2.png","1000000005","","region/index.vue"),
  "1000000006": createCommonRouter("cydw","成员单位","cydw2.png","1000000006","","member/index.vue"),
  "1000000007": createCommonRouter("nsjg","安全生产、防灾减灾内设机构","nsjg2.png","1000000007","","member-org-own/index.vue"),
  "1000000008": createCommonRouter("sydw","事业单位","sydw2.png","1000000008","","entity/list.vue"),
  "1000000009": createCommonRouter("ldbz","单位领导","ldbz2.png","1000000009","","people/index.vue"),
  "1000000010": createCommonRouter("jydw","救援队伍","jydw2.png","1000000010","","manager/statistics/index.vue"),
  "1000000011": createCommonRouter("yjwz","应急物资","yjwz2.png","1000000011","","manager/statistics/index.vue"),
  "1000000012": createCommonRouter("fhmb","防护目标","fhmb2.png","1000000012","","manager/statistics/index.vue"),
  "1000000013": createCommonRouter("zjk","专家库","zjk2.png","1000000013","","manager/statistics/index.vue"),
  "1000000014": createCommonRouter("bncs","避难场所","bncs2.png","1000000014","","manager/statistics/index.vue"),
  "1000000015": createCommonRouter("zhtx","指挥体系成员","zhtx2.png","1000000015","","manager-list/index.vue"),
  "1000000016": createCommonRouter("gzct","嘎查、村、屯","zhtx2.png","1000000016","","region-village/index.vue"), 
  "1000002024": createCommonRouter("xtsqcx","授权查询","zhtx2.png","1000002024","","systemManage/authLog/index.vue"), 
  //转换二类菜单
  "2000000001": createCommonRouter("dwcy","党委成员","","1000000001","2000000001","manager-list/index.vue"),
  "2000000002": createCommonRouter("zfcy","政府成员","","1000000002","2000000002","manager-list/index.vue"),
  "2000000017": createCommonRouter("gwcy","工委成员","","1000000017","2000000017","manager-list/index.vue"),
  "2000000016": createCommonRouter("gzctcy","嘎查、村、屯人员","","1000000016","2000000016","manager-list/index.vue"),
  "2000000013": createCommonRouter("zjkcy","专家成员","","1000000013","2000000013","entity/list.vue"),
  "2000000007": createCommonRouter("nsjgcy","内设机构成员","","1000000007","2000000007","people/index.vue"),
  "2000000014": createCommonRouter("bncs-list","避难场所列表","","1000000014","2000000014","entity/list.vue"),
  "2000000010": createCommonRouter("jydw-list","救援队伍列表","","1000000010","2000000010","entity/list.vue"),
  "2000000011": createCommonRouter("jywz-list","应急物资列表","","1000000011","2000000011","entity/list.vue"),
  "2000000012": createCommonRouter("fhmb-list","防护目标列表","","1000000012","2000000012","entity/list.vue"),
  
  //转换三类菜单
  "3000000010": {
    path: '', 
    component: Layout,    
    meta: {  },
    name: `TeamAdministrator-layout`,
    children: [
      {
        path: "/TeamAdministrator",
        name: "Team-Administrator",
        component: () => import("@/view/resourceManagement/TeamAdministrator/index.vue"),
        meta: { title:"救援队伍", icon: "", noCache: true,query:{menuId:"1000000010"}, menuKey:"3000000010" }
      },
    ]
  },
  "3000000011": {
    path: '',
    component: Layout,
    meta: {},
    name: 'add-material-warehouse-layout',
    hidden: true,
    children: [
      {
        path: "/addMaterialWarehouse",
        name: "add-material-warehouse",
        component: () => import("@/view/takeRefuge/index.vue"),
        meta: { title: "应急物资", icon: "", noCache: true, query: { menuId: "1000000011" }, menuKey: "3000000011" }
      },
    ]
  },
  "3000000012": {
    path: '',
    component: Layout,
    meta: {},
    name: 'protectionTargetAdministrator-layout',
    hidden: true,
    children: [
      {
        path: "/protectionTargetAdministrator",
        name: "protectionTarget-Administrator",
        component: () => import("@/view/protectionTargetAdministrator/index.vue"),
        meta: { title: "防护目标", icon: "", noCache: true, query: { menuId: "1000000012" }, menuKey: "3000000012" }
      },
    ]
  },
  "3000000014": {
    path: '',
    component: Layout,
    meta: {},
    name: `maintenanceInformation-layout`,
    children: [
      {
        path: `/maintenanceInformation`,
        name: `maintenanceInformation`,
        component: () => import("@/view/takeRefuge/maintenanceInformation.vue"),
        meta: { title: "避难场所", icon: "", noCache: true, query: { menuId: "1000000014" }, menuKey: "3000000014" }
      },
    ]
  },
}
//超级管理员:1(所有菜单权限都有)
// 自治区超级管理员:2(菜单)
// 盟市指挥体系管理员:3(菜单)
// 旗县指挥体系管理员:4(菜单)
// 乡镇指挥体系管理员:5(菜单)
// 嘎查村屯管理员:6(菜单)
// 成员单位管理员:7(成员单位菜单)
// 内设机构管理员:8(内设机构菜单)
// 党委领导管理员:9;
// 政府管理员:10;

// 专家库管理员:13;
// 避难场所管理员:14;
// 救援队伍管理员:17
// 事业单位管理员:18
// 普通用户:0

//  登录信息返回，遍历menuPermission去匹配生成路由菜单，如果匹配menuChangeMap（menuPermission + adminType + pageType）中的key，则替换成value的值对应菜单。
let menuChangeMap={
  //[原始菜单:二转菜单:三转菜单]   【页面id：admintype：pagetype】
  "1000000001:9":"2000000001",
  "1000000002:10":"2000000002",
  "1000000017:17":"2000000017",
  "1000000016:6":"2000000016",
  "1000000013:13:3":"2000000013", 
  "1000000014:14:2":"2000000014", 
  "1000000010:17:2":"2000000010",
  "1000000010:17:3":"3000000010",
  "1000000012:12:2":"2000000012",
  "1000000011:11:2":"2000000011",
  "1000000007:8":"2000000007",
  "1000000010:10:3":"3000000010",
  "1000000011:11:3":"3000000011",
  "1000000012:12:3":"3000000012",
  "1000000014:14:3":"3000000014",
}

const baseRouters = [
  {
    path: "/",
    name: "index",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    hidden: true,
    component: () => import("@/view/login/login.vue"),
  },  
 
  {
    path: '', 
    component: Layout,    
    meta: {  },
    name: 'dept-list-layout',
    hidden: true,
    children: [
      {
        path: '/dept/list',
        component: () => import("@/view/dashboard/index.vue"),
        name: 'dept-list',
        meta: { title: '盟市指挥体系', icon: "", noCache: true }
      },
    ]
  },
  {
    path: '', 
    component: Layout,    
    meta: {  },
    name: 'leader-group-layout',
    hidden: true,
    children: [
      {
        path: '/leaderGroup',
        component: () => import("@/view/leaderGroup/index.vue"),
        name: 'leader-group',
        meta: { title: '单位领导', icon: "", noCache: true , query:{id:""}}
      },
    ]
  },
  {
    path: '',
    component: Layout,
    name: 'TeamAdministrator-layout',
    hidden:true,
    children: [
      {
        path: "/TeamAdministrator",
        name: "Team-Administrator",
        component: () => import("@/view/resourceManagement/TeamAdministrator/index.vue"),
      },
    ]
  },
  {
    path: '',
    component: Layout,
    name: 'maintenance-information-layout',
    hidden:true,
    children: [
      {
        path: "/maintenanceInformation",
        name: "maintenance-information",
        component: () => import("@/view/takeRefuge/maintenanceInformation.vue"),
      },
    ]
  },
  {
    path: '',
    component: Layout,
    name: 'add-material-warehouse-layout',
    hidden:true,
    children: [
      {
        path: "/addMaterialWarehouse",
        name: "add-material-warehouse",
        component: () => import("@/view/takeRefuge/index.vue"),
      },
    ]
  },
  {
    path: '',
    component: Layout,
    name: 'protectionTargetAdministrator-layout',
    hidden: true,
    children: [
      {
        path: "/protectionTargetAdministrator",
        name: "protectionTarget-Administrator",
        component: () => import("@/view/protectionTargetAdministrator/index.vue"),
      },
    ]
  },
  {
    path: "/403",
    name: "403",
    component: () => import("@/view/error/403.vue"),
  }, 
];

// 需要通过后台数据来生成的组件



import dbl from "@/utils/dbl";


const createRouter = () =>{
  let userRouters=dbl.get("userRouters"); 
  
  let allRouters=[];
  for (let ri = 0; ri < baseRouters.length; ri++) { 
    allRouters.push(baseRouters[ri])
  }

  if(userRouters && userRouters.length>0){
    for (let ri = 0; ri < userRouters.length; ri++) {
      const ur = userRouters[ri];
      const r=routerMap[ur.children[0].meta.menuKey]
      if(r)allRouters.push(r)      
    } 
  }

  console.log("allRouters", allRouters);
  return new Router({
    base: process.env.VUE_APP_BASE_ROUTER,
    mode: "hash",
    scrollBehavior: () => ({ y: 0 }),
    routes: allRouters,
  });
}

const router = createRouter(); 

// 重置路由  比如切换角色 需要重置路由基础配置
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});
export default router;

export const constantRouterMap=baseRouters



export const asyncRouterMap = []


function getChangeMenu(menuId, admin){
  console.log(admin);
  let key=menuId+":"+admin.adminType
  if(admin.pageType){
    key+=":"+admin.pageType
  }
  console.log('getChangeMenu',key);
  let newMenu=menuChangeMap[key]
  return newMenu?newMenu:menuId
}

export function getUserRouter(permission, admin) {
  if(!permission || permission.length==0){
    return []
  }
  permission=permission.replace(new RegExp(":","g"), ",")
  let userRouters=[]
  let menuIds=permission.split(",");
  for (let mi = 0; mi < menuIds.length; mi++) { 
    const newMenuId=getChangeMenu(menuIds[mi], admin)
    const r=routerMap[newMenuId]
    if(r)  userRouters.push(r)
  }
  console.log('getUserRouter', userRouters)
  return userRouters
}

